# Welcome to the Mobile Hub

The Mobile Hub is an extension of the Scalable Layer Data Distribution that acts as a middleware to allow personal mobile devices to become IoT propagator nodes

The Mobile Hub (M-Hub) is a general-purpose middleware that enables mobile personal devices (Android smartphones and tablets) to become the propagator nodes (i.e. gateways to the Internet) for the simpler IoT objects or Mobile Objects (M-OBJ) (sensors/actuators) with only short-range WPAN interfaces. It provides context information such as current local time and/or the (approximate) location to the data obtained from the M-OBJs to which it is connected. The M-Hub is the natural extension of the Scalable Data Distribution Layer (SDDL).

## Global View

![Architecture](http://download-codeplex.sec.s-msft.com/Download/SourceControlFileDownload.ashx?ProjectName=mobilehub&changeSetId=90849845089d67ba183087a05680a66d84d3da09&itemId=imgs%2farch.png)

## Sequence Diagram

![Sequence Diagram](http://download-codeplex.sec.s-msft.com/Download/SourceControlFileDownload.ashx?ProjectName=mobilehub&changeSetId=18dfa89daa735239617a6daa3be972fad90ecb36&itemId=imgs%2fsequence.png)

# Mobile Hub

![Sequence Diagram M-Hub application](http://download-codeplex.sec.s-msft.com/Download/SourceControlFileDownload.ashx?ProjectName=mobilehub&changeSetId=98c7bff2f2c50d9ae5c9342b0bdface3df427141&itemId=imgs%2fsequence1.png)

## Sending Messages to the Mobile Hub

SDDL Core applications can send ApplicationMessages to Mobile Nodes, being the M-Hub a special kind of it. Nevertheless, the M-Hub only allows a certain kind of messages that can change its behaviour. To do that, the content object in the message must be a JSON String. There are numerous JSON libraries for Java, in the following code we will use Simple-JSON. The following code shows a sample JSON message of the current allowed operation. It allows the modification of the MEPA service. 

```
{
 "MEPAQuery": {
  "type":"add|remove|start|stop|clear|get",
  "label":"AVGTemp",
  "object":"rule|event",
  "rule":"SELECT avg(sensorValue[1]) as value FROM 
      SensorData(sensorName='Temperature')
      .win:time_batch(10 sec)",
  "target":"local|global"
 }
}

```
```
JSONObject jsonMSG = new JSONObject();
// Build the JSON message
ApplicationMessage msg = new ApplicationMessage();
msg.setContentObject( jsonMSG.toString() );
msg.setPayloadType( PayloadSerialization.JSON );
// Send it!!
nodeCon.sendMessage( msg );

```

Examples of allowed CEP rules: 

```
SELECT avg(sensorValue[0]) FROM SensorData(sensorName='Humidity').win:time_batch(1 minute);

SELECT Math.sqrt(Math.pow(avg(sensorValue[0]), 2.0) + Math.pow(avg(sensorValue[1]), 2.0) + Math.pow(avg(sensorValue[2]), 2.0)) as value from SensorData(sensorName='Accelerometer').win:time_batch(1 minute);

SELECT * FROM SensorData(sensorName='Temperature') match_recognize ( measures A as temp1, B as temp2, C as temp3, D as temp4 pattern (A B C D) define A as A.sensorValue[0] > 20, B as (A.sensorValue[0] < B.sensorValue[0]), C as (B.sensorValue[0] < C.sensorValue[0]), D as (C.sensorValue[0] < D.sensorValue[0]));

```

## Handling the messages in the server

A small example of how you can parse such data on a processing node (You can also use the [Hakke](http://www.lac.inf.puc-rio.br/dokuwiki/doku.php?id=hakke) tool), and realize some further processing.

```
@Override
public void onNewData( ApplicationObject topicSample ) {
	if( topicSample instanceof Message ) {
		Message msg = (Message) topicSample;
		String content = new String( msg.getContent() );
		JSONParser parser = new JSONParser();
 
		try {
	                JSONObject object = (JSONObject) parser.parse( content );
	                String tag = (String) object.get( "tag" );
 
	        	switch( tag ) {
	        		case "SensorData":
	        			handleSensorData( object );
	        		break;
 
	        		case "EventData":
	        			final String label = (String) object.get( "label" );
	        			final String data  = (String) object.get( "data" );
	        			handleEvent( label, data );
		        	break;
 
	        		case "ReplyData":		        	
	        		case "ErrorData":
	        			handleMessage( tag, object );
			        break;
	        	}
		} catch( Exception ex ) {
			System.out.println( ex.getMessage() );
		}
	}
}

```

## Troubleshooting

The Mobile Hub makes use of Asper, a version of ESPER(CEP) for Android. When compiling, In some cases (most) it will require some configurations that depending on the IDE could be in the eclipse.ini (Eclipse) or in the studio.vmptions (Android Studio). In the case of Android Studio your file should look as follows: 

```
-server
-Xms512m
-Xmx1024m
-XX:MaxPermSize=1024m
-XX:ReservedCodeCacheSize=150m
-XX:+UseConcMarkSweepGC
-XX:SoftRefLRUPolicyMSPerMB=50
-ea
-Djna.nosys=true
-Djna.boot.library.path=

-Djna.debug_load=true
-Djna.debug_load.jna=true
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-Dawt.useSystemAAFontSettings=lcd

```

 A similar configuration in the parameters Xms (initial memory allocation pool), Xmx (maximum memory allocation pool), and XX:MaxPermSize will be required in the eclipse.ini file.

